﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using LIT.Logger.Client;

namespace LIT.Logger.ServerCheckerBL.Checkers
{
    public class DiskLimit
    {
        private IEventSender m_eventSender;
        private IConfiguration m_config;

        public DiskLimit(IEventSender _eventSender, IConfiguration _config)
        {
            if (_eventSender == null)
                throw new ArgumentNullException("_eventSender");
            if (_config == null)
                throw new ArgumentNullException("_config");
            this.m_eventSender = _eventSender;
            this.m_config = _config;
        }

        public void CheckDrives()
        {
            foreach (char driveLetter in m_config.CheckLowDiskSpaceDriveLetters)
            {
                this.CheckSpace(driveLetter);
                m_eventSender.ReportEvent(new Event("Drive checked", EventType.DEBUG, "Drive: " + driveLetter));
            }
        }

        private void CheckSpace(char _driveLetter)
        {
            long freeSpace = -1;
            try
            {
                freeSpace = GetDiskSpaceMB(_driveLetter);
                if (m_config.DiskSpaceLowLimitMB > freeSpace)
                {
                    this.m_eventSender.ReportEvent(
                        new Event("Server disk space too low.", EventType.ERROR) 
                        {
                            Details = string.Format("Free space on drive {0}: {1} Mb.", _driveLetter, freeSpace) 
                        });
                }
                
            }
            catch (Exception ex)
            {
                this.m_eventSender.ReportException(new ExceptionEvent("Querying Disk space failed", EventType.ERROR, ex)
                {
                    Details = string.Format("Drive: {0}:", _driveLetter)
                });
            }
        }

        private long GetDiskSpaceMB(char _driveLetter)
        {
            ManagementObject disk = new ManagementObject(string.Format("win32_logicaldisk.deviceid=\"{0}:\"", _driveLetter));
            disk.Get();

            object freeSpaceObj = disk["FreeSpace"];

            return long.Parse(freeSpaceObj.ToString()) / (1024*1024);
        }
    }
}
